package main

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"sync"
	"time"
)

var (
	count int
	mu    sync.Mutex
	limit chan struct{}
)

func main4() {

	r := gin.Default()
	limit = make(chan struct{}, 10)

	r.GET("/counter", func(c *gin.Context) {
		mu.Lock()
		defer mu.Unlock()
		c.JSON(http.StatusOK, gin.H{
			"counter": count,
		})
	})
	r.POST("/counter", func(c *gin.Context) {
		select {
		case limit <- struct{}{}:
			mu.Lock()
			count++
			mu.Unlock()
			c.JSON(http.StatusOK, gin.H{
				"counter": count,
			})
			go func() {
				time.Sleep(time.Second)
				<-limit
			}()
		default:
			c.JSON(http.StatusTooManyRequests, gin.H{"msg": "too many req"})
		}
	})
	r.Run("8080")
}
